package com.cs.user.controller;


import com.cs.common.result.HttpResp;
import com.cs.common.result.ResultCode;
import com.cs.domain.entity.User;
import com.cs.tools.service.IEmailService;
import com.cs.tools.util.JwtUtil;
import com.cs.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private IUserService ius;

    @Autowired
    private IEmailService ies;


    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @GetMapping("/sendEmail")
    public HttpResp sendEmail(String email) {
        Random random = new Random();
        //产生验证码
        int t = random.nextInt(8999) + 1000;
        //将生成的验证码和用户输入的邮箱存入redis缓存中，并设置过期时间为3分钟
        stringRedisTemplate.opsForValue().set(email, String.valueOf(t), 180, TimeUnit.SECONDS);
        //发送验证码
        ies.sendEmail(email, "luckyMarket用户注册验证码", "验证码:" + String.valueOf(t) + ".验证码3分钟之内有效，请勿泄漏与他人");
        return HttpResp.result(ResultCode.EMAIL_SEND_SUCCESS, new Date(), null);
    }


    @PostMapping("/register")
    public HttpResp register(String username,  String password,  String email,  String code) {

        if ((username != "" && username != null) && (password != "" && password !=null)){
            if (code.equals("")){
                return HttpResp.result(ResultCode.CODE_INPUT_NULL, new Date(), null);
            }else if (stringRedisTemplate.hasKey(email)){
                if (stringRedisTemplate.opsForValue().get(email).equals(code)){
                    boolean isRegister = ius.register(username, password, email);
                    if (isRegister == true){
                        return HttpResp.result(ResultCode.USER_USERNAME_EXIST,new Date(),null);
                    }else {
                        return HttpResp.result(ResultCode.USER_REGISTER_SUCCESS, new Date(), null);
                    }

                }else {
                    return HttpResp.result(ResultCode.CODE_INPUT_ERROR, new Date(), null);
                }
            }else {
                return HttpResp.result(ResultCode.CODE_exist_NO, new Date(), null);
            }
        }else {
            return HttpResp.result(ResultCode.USER_REGISTE_ERROE,new Date(),null);
        }




    }

    @GetMapping("/login")
    public HttpResp login(String username, String password,HttpServletResponse response){
        List<User> list = ius.login(username,password);
        if (list.size()==0){
            return HttpResp.result(ResultCode.USER_LOGIN_ERROR,new Date(),null);
        }
        Map<String ,String> map = new HashMap<>();
        map.put("username",username);
        map.put("role",list.get(0).getRole());
        String token = JwtUtil.createToken(username,list.get(0).getRole(),1000 *5* 60 * 1000);
        stringRedisTemplate.opsForValue().set(username,token,30, TimeUnit.MINUTES);
        map.put("token",token);
        response.addHeader("token",token);
        return HttpResp.result(ResultCode.USER_LOGIN_SUCCESS,new Date(),map);
    }

    @GetMapping("/logout")
    public HttpResp logout(String username, HttpServletResponse response){
        stringRedisTemplate.delete(username);
        return HttpResp.result(ResultCode.USER_LOGIN_SUCCESS,new Date(),null);
    }

    @GetMapping("/deleteUserById")
    public HttpResp deleteUserById(long id){
        ius.deleteUserById(id);
        return HttpResp.result(ResultCode.USER_DELETE_SUCCESS,new Date(),null);
    }

    @PostMapping("/updateUser")
    public HttpResp updateUser(User user){
        Integer updateOne = ius.updateUser(user);
        return HttpResp.result(ResultCode.USER_UPDATE_ID_SUCCESS,new Date(),updateOne);
    }

}

